<?php

$page = "signup";

require 'require.php';

if (isset($_SESSION['user_id']) && ($_SESSION['user_id'])) {
	header("Location: index.php");
	exit;
}

$display_error = array();

if (isset($_POST['oir_action']) && ($_POST['oir_action'] == 'registration')) {



	$link_server = mysql_connect(OPENIDOO_DB_SERVER, OPENIDOO_DB_USER, OPENIDOO_DB_PASSWORD);
	$select_db = mysql_select_db(OPENIDOO_DB_DATABASE, $link_server);

	if ((!$link_server) or (!$select_db)) {
		die('Impossible de se connecter');
	} else {
	
		if (!(isset($_POST['oir_username']) && (mb_strlen($_POST['oir_username']) > 2))) {
			$display_error[] = 'username';
		} else {
			if(!eregi("^[0-9a-zA-Z]+$" , $_POST['oir_username'])){
				$display_error[] = 'carac';
			}else{
				if (!($check_username = mysql_query("SELECT user_id, username FROM openidoo_accounts WHERE username='".mysql_escape_string($_POST['oir_username'])."' LIMIT 1", $link_server))) {
					die('Une erreur est survenue');
				} else {
					if (mysql_num_rows($check_username) != 0) {
						$display_error[] = 'check_username';
					}
				}
			}
		}

		if (!(isset($_POST['oir_password']) && (mb_strlen($_POST['oir_password']) > 2))) {
			$display_error[] = 'password';
		}

		if (!(isset($_POST['oir_password_confirm']) && ($_POST['oir_password'] == $_POST['oir_password_confirm']))) {
			$display_error[] = 'password_confirm';
		}

		if (!(isset($_POST['oir_mail']) && (eregi("(^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$)", $_POST['oir_mail'])))) {
			$display_error[] = 'mail';
		}

		if (count($display_error) == 0) {

			if (!mysql_query("INSERT INTO openidoo_accounts (identity, username, password, email) VALUES ('".mysql_escape_string(str_replace('www.', '', OPENIDOO_DOMAIN))."/".mysql_escape_string($_POST['oir_username'])."', '".mysql_escape_string($_POST['oir_username'])."', '".mysql_escape_string($_POST['oir_password'])."', '".mysql_escape_string($_POST['oir_mail'])."')", $link_server)) {
				die('Une erreur est survenue');
			}

			$_SESSION['user_id'] = mysql_insert_id();
			$_SESSION['username'] = $_POST['oir_username'];
			$_SESSION['password'] = $_POST['oir_password'];

			mysql_query("INSERT INTO openidoo_personas (user_id, default, persona_name) VALUES ('".mysql_escape_string($_SESSION['user_id'])."', '1', 'Default')", $link_server);

			header("Location: index.php");
			exit;
		}
	
	}
}

require "html/top.html";
require "html/signup.html";
require "html/bottom.html";

?>
